package com.doubao.auth.client;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "sms.jumdata")
public class JumdataSmsClient {

    private String appId;
    private String appSecret;
    private String url = "https://api.jumdata.com/sms/send";
    private String productCode = "sms";
    private String templateId;

    private final RestTemplate restTemplate;

    public JumdataSmsClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 发送短信验证码
     * @param phoneNumber 接收验证码的手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendVerificationCode(String phoneNumber, String code) {
        try {
            long timestamp = System.currentTimeMillis();
            String sign = DigestUtils.sha256Hex(appId + appSecret + timestamp);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("appId", appId);
            params.add("timestamp", String.valueOf(timestamp));
            params.add("sign", sign);
            params.add("productCode", productCode);
            params.add("receive", phoneNumber);
            params.add("templateId", templateId);
            params.add("values", code);

            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);

            Map<String, Object> response = restTemplate.postForObject(url, request, Map.class);

            log.info("短信发送结果: {}", response);

            return response != null && response.get("code").equals(200);
        } catch (Exception e) {
            log.error("发送短信验证码异常", e);
            return false;
        }
    }
}